package net.imagine.backend.mockrmi.remote.provider.netty.client;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.WriteCompletionEvent;

/**
 * Netty实现的客户端IO处理类
 * 
 * @author wuqh
 * @see SimpleChannelUpstreamHandler
 */
public class NettyClientIoHandler extends SimpleChannelUpstreamHandler {
	private static final Log logger = LogFactory.getLog(NettyClientIoHandler.class);

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		logger.error("client occurred an unexpected excpetion", e.getCause());
		ctx.getChannel().close().awaitUninterruptibly();
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		ctx.setAttachment(e.getMessage());
		logger.debug("Client:message received");
	}

	@Override
	public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e) throws Exception {
		logger.debug("Client:message sended");
	}

	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		logger.debug("Client:channel closed");
	}

	@Override
	public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		logger.debug("Client:channel opened");
	}
}
